import uuid
from datetime import datetime
from io import BytesIO

from django.db.models import Q
from django.http import JsonResponse
from django.shortcuts import render, HttpResponse, redirect

from utils.image_code import check_code
from web import models
from web.forms.account import RegisterModelForm, LoginSMSForm, LoginForm
from web.forms.account import SendSmsForm


def register(request):
    """注册"""
    if request.method == 'GET':
        form = RegisterModelForm()
        return render(request, 'register.html', {'form': form})
    
    form = RegisterModelForm(data=request.POST)
    if form.is_valid():
        # 验证通过 保存数据
        
        instance = form.save()  # 本句等同于下句
        # instance = models.UserInfo.objects.create(**form.cleaned_data)
        
        # 创建交易记录
        policy_obj = models.PricePolicy.objects.filter(category=1, title='个人免费版').first()
        models.Transaction.objects.create(
            status=2,
            order_num=str(uuid.uuid4()),
            user=instance,
            price_policy=policy_obj,
            count=0,
            price=0,
            start_time=datetime.now()
        )
        
        return JsonResponse({'status': True, 'data': '/login/'})
    return JsonResponse({'status': False, 'error': form.errors})


def send_sms(request):
    """发送短信"""
    
    form = SendSmsForm(request, data=request.GET)
    
    if form.is_valid():
        return JsonResponse({'status': True})
    
    return JsonResponse({'status': False, 'error': form.errors})


def login_sms(request):
    
    """短信登录"""
    if request.method == 'GET':
        
        form = LoginSMSForm()
        return render(request, 'login_sms.html', {'form': form})
    form = LoginSMSForm(request.POST)
    if form.is_valid():
        # 获取数据 保存到session
        phone = form.cleaned_data.get('phone')
        user_obj = models.UserInfo.objects.filter(phone=phone).first()
        request.session['user_id'] = user_obj.id
        request.session.set_expiry(60 * 60 * 24 * 14)
        
        return JsonResponse({'status': True, 'data': '/index/'})
    return JsonResponse({'status': False, 'error': form.errors})


def login(request):
    
    """密码登录"""
    if request.method == 'GET':
        form = LoginForm(request)
        return render(request, 'login.html', {'form': form})
    
    form = LoginForm(request, data=request.POST)
    if form.is_valid():
        
        name = form.cleaned_data['name']
        password = form.cleaned_data['password']
        # user_obj = models.UserInfo.objects.filter(name=name, password=password).first()
        # 复杂的查询使用Q
        user_obj = models.UserInfo.objects.filter(Q(email=name) | Q(phone=name)).filter(password=password).first()
        
        if user_obj:
            request.session['user_id'] = user_obj.id
            request.session.set_expiry(60 * 60 * 24 * 14)
            
            # 重定向到index
            return redirect('/index/')  # ?什么时候加/
        form.add_error('name', '用户名或密码错误')
        
    return render(request, 'login.html', {'form': form})


def logout(request):
    """注销"""
    
    # 清空session
    request.session.flush()
    
    return redirect('/index/')


def image_code(request):
    
    """生成图片验证并返回给前端"""
    
    image_obj, code = check_code()
    
    # 把验证信息写到session
    request.session['image_code'] = code
    # 设置session有效时间 60s
    request.session.set_expiry(60)
    
    # 把图片数据写到内存
    stream = BytesIO()
    image_obj.save(stream, 'png')
    
    return HttpResponse(stream.getvalue())
